package com.ihai.spring.boot.sample.distributed.counter.listener;

import com.ihai.spring.boot.sample.distributed.counter.manager.CounterManager;
import com.ihai.spring.boot.sample.distributed.counter.remote.Node;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * DESC
 *
 * @author 张驰
 * @date 2019/12/26
 */
@Component
public class NodeListener implements ApplicationListener<NodeChangeEvent> {
    @Override
    public void onApplicationEvent(NodeChangeEvent event) {
        Node current = new Node();
        if(event.getCurrent().contains("]")){
            current.setIp(event.getCurrent().substring(0, event.getCurrent().lastIndexOf(":")));
            current.setPort(Integer.parseInt(event.getCurrent().substring(event.getCurrent().lastIndexOf(":"))+1));
        }else{
            String[] arr = event.getCurrent().split(":");
            current.setIp(arr[0]);
            current.setPort(Integer.parseInt(arr[1]));
        }
        CounterManager.getInstance().setCurrent(current);
        List<String> strNodes = event.getClusters();
        List<Node> nodes = new ArrayList<>();
        for(String url : strNodes){
            Node node = new Node();
            if(url.contains("]")){
                node.setIp(url.substring(0, url.lastIndexOf(":")));
                node.setPort(Integer.parseInt(url.substring(url.lastIndexOf(":")+1)));
            }else{
                String[] arr = url.split(":");
                node.setIp(arr[0]);
                node.setPort(Integer.parseInt(arr[1]));
            }
            nodes.add(node);
        }
        CounterManager.getInstance().setClusters(nodes);

    }
}
